<template>
  <div class="selector-container">
    <el-input :disabled="true" v-model="showUserNames" placeholder="请输入内容" style="flex: 1" />
    <el-button v-if="!disabled" type="primary" style="margin-left: 12px" @click="selectUser">选择</el-button>
    <org-picker :title="pickerTitle" multiple type="user" ref="orgPicker" :isRadio="isRadio" :selected="users" @ok="doSelected" />
  </div>
</template>
<script>
export default {
  name: 'UserSelector',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    isRadio: {
      type: Boolean,
      default: false
    },
    modelValue: {
      type: Array,
      default: () => []
    },
    format: {
      type: String,
      default: ''
    },
    beforeSelect: {
      type: Function,
      default: () => {}
    },
    selected: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      users: [],
      pickerTitle: '请选择人员',
      orgPickerSelected: []
    };
  },
  computed: {
    showUserNames() {
      if (this.users) {
        return this.users
          .map((user) => {
            const { userId, userName, loginName } = user;
            let str = this.format
              .replaceAll('userId', userId || '')
              .replaceAll('userName', userName || '')
              .replaceAll('loginName', loginName || '');
            return str;
          })
          .join(',');
      } else {
        return '';
      }
    }
  },
  watch: {
    modelValue: {
      handler(newVal) {
        this.users = newVal;
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    selectUser() {
      if(this.beforeSelect && typeof this.beforeSelect === 'function'){
        this.beforeSelect()
      }
      this.$refs.orgPicker.show();
    },
    doSelected(select) {
      this.users = select;
      this.$emit('update:modelValue', this.users);
      if(this.selected && typeof this.selected === 'function'){
        this.selected(select);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.selector-container {
  width: 100%;
  display: flex;
  align-items: center;
}
</style>